package handler

import (
	"encoding/json"
	"fmt"
	"time"

	"gitee.com/yutiandou/wdtools/wdlog"

	"gitee.com/yutiandou/wdRPC/common/connect"
	"gitee.com/yutiandou/wdRPC/common/routing"
)

var routtable = routing.NewRoutingTable()

//添加和删除事件
type Connhand struct {
	connect.PoolHandler
}

func (c *Connhand) Delete(n *connect.NetNode) {
	routnode := &routing.Node{
		NodeName: n.NodeName,
		Address:  n.Address,
	}
	routtable.DeleteNode(routnode)
}
func (c *Connhand) Add(n *connect.NetNode) {

}

//Purpose_NewNode 新节点到达
func Purpose_NewNode_1(node *connect.NetNode, data []byte) {
	var nodeinfo = &routing.Node{}
	err := json.Unmarshal(data, nodeinfo)
	if wdlog.Error(err) {
		node.Write(1, connect.Warn_node_offset)
		return
	}
	node.NodeName = nodeinfo.NodeName
	node.Address = nodeinfo.Address
	routtable.AddrOrUpdateNode(nodeinfo)
	node.Write(1, connect.Success_Connect)
}

//Purpose_NewClient_2 ..请求最新的路由表
func Purpose_NewClient_2(node *connect.NetNode, data []byte) {
	routname := string(data)
	if list, err := routtable.GetRoutTableByName(routname); wdlog.Error(err) {
		resp := &connect.Warn{
			Error: 200,
			Data:  list,
		}
		listinfo, err := json.Marshal(resp)
		if wdlog.Error(err) {
			node.Write(2, listinfo)
			return
		}
	}
	node.Write(2, connect.Warn_Server_fail)
}

//Loopup_Timing 心跳
func Loopup_Timing(pool *connect.ConnPool) {
	go func() {
		for {
			<-time.After(time.Second * 100)
			pool.Range(func(netnode *connect.NetNode) {
				netnode.Write(1, connect.HeartBeat)
			})
		}
	}()
}

//ErgodicRoutTable ..打印路由表信息 //可以作为所有主机的监控
func ErgodicRoutTable() {
	go func() {
		for {
			<-time.After(time.Second * 10)
			routtable.ErgodicAllNode(func(node *routing.Node) {
				fmt.Println(node)
			})
		}
	}()
}
